package com.hancher.common.androidutil;

import android.os.Environment;
import android.os.StatFs;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/5/13 15:38 <br/>
 * 描述 : 手机存储大小
 */
public class StorageUtil {

    public enum Unit {
        BYTE,
        KB,
        MB,
        GB,
        TB
    }

    /**
     * 获得存储使用情况
     * @param unit 获取的大小
     * @param keepDigit 保留位数
     * @return [未使用, 已使用, 总计]
     */
    public static List<BigDecimal> getStorage(MemoryUtil.Unit unit, int keepDigit) {
        File root = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(root.getPath());
        BigDecimal avail = new BigDecimal(sf.getBlockSizeLong()).multiply(new BigDecimal(sf.getAvailableBlocksLong()));
        BigDecimal total = new BigDecimal(sf.getBlockSizeLong()).multiply(new BigDecimal(sf.getBlockCountLong()));
        BigDecimal used = total.subtract(avail);
        avail = changeMemoryDigit(avail, MemoryUtil.Unit.BYTE, unit, keepDigit);
        total = changeMemoryDigit(total, MemoryUtil.Unit.BYTE, unit, keepDigit);
        used = changeMemoryDigit(used, MemoryUtil.Unit.BYTE, unit, keepDigit);
        return Arrays.asList(avail, used, total);
    }

    private static BigDecimal changeMemoryDigit(BigDecimal data, MemoryUtil.Unit srcUnit, MemoryUtil.Unit originUnit, int keepDigit) {
        BigDecimal d = new BigDecimal("1024").pow(originUnit.ordinal() - srcUnit.ordinal());
        return data.divide(d, keepDigit, RoundingMode.HALF_UP);
    }
}
